package a07_二叉树;

/**
 * <p>
 * a18_从中序与后序遍历序列构造二叉树复习3
 * </p>
 *
 * @author flyduck
 * @since 2025/4/14
 */
public class a18_从中序与后序遍历序列构造二叉树复习3 {

    public static void main(String[] args) {
        a18_从中序与后序遍历序列构造二叉树复习3 test = new a18_从中序与后序遍历序列构造二叉树复习3();
        test.buildTree(new int[]{9,3,15,20,7},new int[]{9,15,7,20,3});
    }
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if (inorder.length == 0) {
            return null;
        }
        int rootVal = postorder[postorder.length - 1];
        int rootIdx = -1;
        for (int i = 0; i < inorder.length; i++) {
            if(inorder[i] == rootVal){
                rootIdx = i;
            }
        }

        int[] leftInorder = split(inorder, 0, rootIdx - 1);
        int[] rightInorder = split(inorder, rootIdx + 1, inorder.length - 1);

        int[] leftPostorder = split(postorder, 0, leftInorder.length - 1);
        int[] rightPostorder = split(postorder, leftInorder.length, postorder.length - 2);

        TreeNode root = new TreeNode(rootVal);
        root.left = buildTree(leftInorder, leftPostorder);
        root.right = buildTree(rightInorder, rightPostorder);
        return root;
    }

    private int[] split(int[] array,int leftIdx,int rightIdx){
        int[] result = new int[rightIdx - leftIdx + 1];
        int newIdx = 0;
        while (leftIdx <= rightIdx) {
            result[newIdx] = array[leftIdx];
            leftIdx++;
            newIdx++;
        }
        return result;
    }
}
